<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="数据库名称" prop="dbName">
        <el-input
          v-model="queryParams.dbName"
          placeholder="请输入数据库名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['database:yetao:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['database:yetao:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['database:yetao:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['database:yetao:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="dbList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="产品ID" width="100" align="center" prop="dbId" />
      <el-table-column label="数据库名称" align="center" prop="dbName" :show-overflow-tooltip="true" />
      <el-table-column label="图标" align="center" width="100">
        <template slot-scope="scope">
          <img v-if="scope.row.icon" :src="scope.row.icon" style="width: 40px; height: 40px;" />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="类型" align="center" prop="type" :show-overflow-tooltip="true" />
      <el-table-column label="数据库描述" align="center" prop="description" :show-overflow-tooltip="true" />
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['database:yetao:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['database:yetao:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改数据库产品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="数据库名称" prop="dbName">
          <el-input v-model="form.dbName" placeholder="请输入数据库名称" />
        </el-form-item>
        <el-form-item label="图标" prop="icon">
          <div class="avatar-uploader">
            <el-upload
              class="avatar-uploader"
              :action="uploadUrl"
              :headers="{ Authorization: getToken() }"
              :show-file-list="false"
              :on-success="handleUploadSuccess"
              :before-upload="handleBeforeUpload"
            >
              <img v-if="form.icon" :src="form.icon" class="avatar" />
              <i v-else class="el-icon-plus avatar-uploader-icon"></i>
            </el-upload>
            <div class="el-upload__tip">请上传大小不超过 5MB 格式为 png/jpg/jpeg 的文件</div>
          </div>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-checkbox-group v-model="typeOptions">
            <el-checkbox label="关系型">关系型</el-checkbox>
            <el-checkbox label="非关系型">非关系型</el-checkbox>
            <el-checkbox label="单机">单机</el-checkbox>
            <el-checkbox label="分布式">分布式</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="数据库描述" prop="description">
          <quill-editor v-model="form.description" :options="editorOption" style="height: 300px;"></quill-editor>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">提交</el-button>
        <el-button @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDb, getDb, delDb, addDb, updateDb, exportDb } from "@/api/database/yetao";
import { getToken } from "@/utils/auth";

export default {
  name: "YeTao",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 数据库产品表格数据
      dbList: [],
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dbName: ""
      },
      // 表单参数
      form: {
        dbId: null,
        dbName: null,
        icon: null,
        type: null,
        description: null,
        remark: null
      },
      // 类型选项
      typeOptions: [],
      // 富文本编辑器配置
      editorOption: {},
      // 上传图片的URL
      uploadUrl: process.env.VUE_APP_BASE_API + "/common/upload",
      // 表单校验
      rules: {
        dbName: [
          { required: true, message: "数据库名称不能为空", trigger: "blur" }
        ]
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询数据库产品列表 */
    getList() {
      this.loading = true;
      listDb(this.queryParams).then(response => {
        this.dbList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        dbId: null,
        dbName: null,
        icon: null,
        type: null,
        description: null,
        remark: null
      };
      this.typeOptions = [];
      this.resetForm("form");
    },
    // 搜索按钮
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    // 重置按钮
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 新增按钮
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加数据库产品";
    },
    // 修改按钮
    handleUpdate(row) {
      this.reset();
      const dbId = row.dbId || this.ids
      getDb(dbId).then(response => {
        this.form = response.data;
        // 处理类型选项
        if (this.form.type) {
          this.typeOptions = this.form.type.split("、");
        }
        this.open = true;
        this.title = "修改数据库产品";
      });
    },
    // 提交按钮
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          // 处理类型选项，转换为字符串
          if (this.typeOptions.length > 0) {
            this.form.type = this.typeOptions.join("、");
          }
          if (this.form.dbId != null) {
            updateDb(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDb(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 删除按钮
    handleDelete(row) {
      const dbIds = row.dbId || this.ids;
      this.$modal.confirm(
        "是否确认删除数据库产品?",
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).then(function() {
        return delDb(dbIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    // 导出按钮
    handleExport() {
      this.download(this.queryParams, "database/yetao/export", "数据库产品数据");
    },
    // 复选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.dbId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    // 上传前校验
    handleBeforeUpload(file) {
      const isImg = ['image/jpeg', 'image/png', 'image/jpg'].includes(file.type);
      const isLt5M = file.size / 1024 / 1024 < 5;
      if (!isImg) {
        this.$message.error('上传图片只能是 JPG/JPEG/PNG 格式!');
      }
      if (!isLt5M) {
        this.$message.error('上传图片大小不能超过 5MB!');
      }
      return isImg && isLt5M;
    },
    // 上传成功回调
    handleUploadSuccess(res, file) {
      if (res.code === 200) {
        this.form.icon = res.url;
      } else {
        this.$message.error(res.msg);
      }
    }
  }
};
</script>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  width: 150px;
  height: 150px;
}
.avatar-uploader .el-upload:hover {
  border-color: #409EFF;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 150px;
  height: 150px;
  line-height: 150px;
  text-align: center;
}
.avatar {
  width: 150px;
  height: 150px;
  display: block;
}
</style>